<template>
  <a-affix :offset-top="20">
    <div class="aside-item">
      <div class="aside-header">这里是目录</div>
      <div class="aside-content">
        <template v-if="cataList && cataList.length">
          <a-anchor>
            <a-anchor-link v-for="(item) in cataList" :key="item" class="catalogue-item"
                           :style="{paddingLeft: item.level * 8 + 'px'}"
                           :href="'#' + item.link" :title="item.name">
            </a-anchor-link>
          </a-anchor>
        </template>
      </div>
    </div>
  </a-affix>
</template>

<script>
import {onMounted, ref} from "vue";
import {onBeforeRouteUpdate} from "vue-router";


export default {
  name: "Catalogue",
  setup() {
    const cataList = ref([]);

    // 根据文章内容的h标签生成目录导航
    const generCatalogues = () => {
      setTimeout(() => {
        const titles = document.querySelectorAll('.article-content h1,.article-content h2,.article-content h3,.article-content h4,.article-content h5')
        const result = []
        titles.forEach(function (currentValue, currentIndex) {
          const level = currentIndex + 1
          result.push({
            level: currentValue.tagName.replace('h', '').replace('H', ''),
            name: currentValue.textContent,
            link: 'head-' + level,
          })
        })
        cataList.value = result;
      }, 500)
    }

    // 页面未跳转，仅路由发生变化
    onBeforeRouteUpdate(() => {
      generCatalogues()
    })


    onMounted(() => {
      generCatalogues()
    })

    return {
      cataList,
    }
  }
}
</script>

<style lang="less" scoped>
.catalogue-item {
  margin: 0;
  padding: 0;
  height: 40px;
  font-size: 1.167rem;
  font-weight: 400;
  line-height: 22px;
  color: #333;
  list-style: none;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
